<?php
/**
 * PHP Class to collect information about Video
 *
 *  author: Abramov Alexander (wl)
 *  web-site: http://www.neotemple.ru/
 *
 **/

class phpffmpeg {

// Bitrate
	var $bitrate = 0;

// Duration
	var $duration = 0;
	var $duration_raw = "";

// Codec Name
	var $vcodec = "";

	var $w = 0;
	var $h = 0;

	var $framerate = "";

	var $acodec = "";
	var $audiorate = "";
	var $channels = "";
	var $audiobitrate = "";

// Construct
	function phpffmpeg( $file ) {
	
	// Global Array of Information
		$lOut = array();

	// Escape a string to be used as a shell argument (* thx to Alexey Zakhlestin *)
		$file = escapeshellarg($file);
	
		$cmd = "/usr/local/bin/ffmpeg -i ".$file." 2>&1";
		exec($cmd, $lOut);

	// We are getting duration of movie
		$lDuration = $this->getLine( '/Duration: (.*?),/', $lOut );
	
		$lArray = explode(':', $lDuration[1]);
		$this->duration = intval($lArray[0] * 3600 + $lArray[1] * 60 + round($lArray[2])); // round for not float
		$this->duration_raw = $lArray[0].":".$lArray[1].":".round($lArray[2]); // raw txt format of time
	
	// Getting Bitrate
		$lBitrate =  $this->getLine( '/, bitrate: (\S+) kb\/s/', $lOut );
	
		$this->bitrate = intval($lBitrate[1]); // get only digits
	
	// Video information
		$lVideoinfo =  $this->getLine( '/Stream #\d+.\d+.*?: Video: (\S+)\, .*?\, (\d+)x(\d+)(,)? .*?\, (.*?) tbr/', $lOut );

		// Codec
		$this->vcodec = $lVideoinfo[1];
		$this->w = intval($lVideoinfo[2]);
		$this->h = intval($lVideoinfo[3]);
		$this->framerate = $lVideoinfo[4];
	
	
	// Audio information
		$lAudioinfo =  $this->getLine( '/Stream #\d+.\d+.*?: Audio: (.*?), (.*?) Hz, (\S+).*?\, .*?\, (\S+) kb/', $lOut );
	
		$this->acodec = $lAudioinfo[1];
		$this->audiorate = $lAudioinfo[2];
		$this->channels = $lAudioinfo[3];
		$this->audiobitrate = $lAudioinfo[4];
	}

/*
 ******************************************
 * Name: getLine()
 *  $inMatch - regexp
 *  &$inArray - global array of data
 *
 * Desc: Search regexp in array
 ******************************************
 */
	function getLine( $inMatch, &$inArray ) {
	
		reset($inArray);
	
		$fResult = array();
	
		$i = 0;
	
		while(($lArr = next($inArray)) !== false) {
			if( preg_match($inMatch, $lArr, $fResult) ) {
				return $fResult;
			}
			$i++;
		}
	
	// No matches found
		return 0;
	}

}
?>